class Solution {
public:
    int orangesRotting(vector<vector<int>>& grid) {
        int dx[4] = {0, 0, -1, 1};
        int dy[4] = {1, -1, 0, 0};
        int m = grid.size(), n = grid[0].size(), ret = -1;
        queue<pair<int, int>> q;
        bool flag = true;
        for(int i = 0; i < m; ++i)
        {
            for(int j = 0; j < n; ++j)
            {
                if(grid[i][j] == 2)
                    q.push({i, j});
                if(grid[i][j] == 1)
                    flag = false;
            }
        }
        if(q.empty() && flag)
            return 0;
        while(!q.empty())
        {
            int sz = q.size();
            for(int k = 0; k < sz; ++k)
            {
                auto [a, b] = q.front();
                q.pop();
                for(int i = 0; i < 4; ++i)
                {
                    int x = a + dx[i], y = b + dy[i];
                    if(x >= 0 && x < m && y >= 0 && y < n && grid[x][y] == 1)
                    {
                        grid[x][y] = 2;
                        q.push({x, y});
                    }
                }
            }
            ++ret;
        }

        for(int i = 0; i < m; ++i)
        {
            for(int j = 0; j < n; ++j)
            {
                if(grid[i][j] == 1)
                    ret = -1;
            }
        }
        return ret;
    }
};